import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { InjectionKey } from 'vue'
import { setItem } from '@/utils/storage'
import { State as User } from './modules/user'
import { State as Permission } from './modules/permission'

export interface State {
  user: User
  permission: Permission
}

const modulesFiles = import.meta.globEager('./modules/*.ts')

const modules = Object.entries(modulesFiles).reduce<Record<string, any>>((accumulator, [k, v]) => {
  const moduleName = k.replace(/(.*\/)*([^.]+).*/gi, '$2')
  accumulator[moduleName] = v.default
  return accumulator
}, {})

const arr = ['permission', 'layout'] // 不进行缓存的store
const myPlugin = (store:Store<State>) => {
  store.subscribe((mutation, state:Record<string, any>) => {
    const localid = mutation.type.split('/')[0] // 截取vuex标识
    if (!arr.includes(localid)) {
      setItem(localid, state[localid])
    }
  })
}

export const key: InjectionKey<Store<State>> = Symbol('store')
// 创建一个新的 store 实例
export const store = createStore<State>({
  plugins: [myPlugin],
  modules
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
